package com.jp.knowledge.fragment;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.model.OrganizeInfoModel;
import com.jp.knowledge.model.PositionKnowlegeMode;

import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/8/15.
 */

public class OrganizeKnowledgeSelectFragment extends AdjustSortTypeFragment implements OrganizeKnowledgeSelectDetailFragment.ItemClickListener {

	private Intent intent;
	private Activity activity;
	private List<OrganizeInfoModel.KnowledgeBean> knowledgeDatas;

	@ViewInject(R.id.right_bn)
	protected TextView rightBtn;

	@Override
	protected void init() {
		activity = getActivity();
		intent = activity.getIntent();
		knowledgeDatas = (List) intent.getSerializableExtra("data");
		super.init();
		titleName.setText("选择关心的知识");
		rightBtn.setText("确定");
		rightBtn.setVisibility(View.VISIBLE);
		rightBtn.setOnClickListener(this);
	}

	@Override
	protected JobKnowledgeDataFragment createFragment(PositionKnowlegeMode mode) {
		OrganizeKnowledgeSelectDetailFragment fragment = OrganizeKnowledgeSelectDetailFragment.newInstance(mode);
		fragment.setItemClickListener(this);
		return fragment;
	}

	@Override
	protected void updateView(List<PositionKnowlegeMode> datas) {
		if(datas != null && knowledgeDatas != null){
			for(PositionKnowlegeMode mode : datas){
				for(PositionKnowlegeMode.ListBeanX listBeanX : mode.getList()){
					if(listBeanX == null)
						continue;
					for(PositionKnowlegeMode.ListBeanX.ListBean listBean : listBeanX.getList()){
						if(listBean == null || listBean.getId() == null)
							continue;
						for(OrganizeInfoModel.KnowledgeBean knowledgeBean : knowledgeDatas){
							if(knowledgeBean != null && listBean.getId().equals(knowledgeBean.getCateId())){
								listBean.setSelect(true);
								break;
							}
						}
					}
				}
			}
		}
		super.updateView(datas);
	}

	@Override
	public void onClick(View v) {
		if(v == rightBtn){
			intent.putExtra("data", (Serializable) knowledgeDatas);
			activity.setResult(Activity.RESULT_OK, intent);
			activity.onBackPressed();
		} else {
			super.onClick(v);
		}
	}

	@Override
	public boolean onItemClick(OrganizeInfoModel.KnowledgeBean data, boolean isSelected) {
		if(isSelected) {
			if(knowledgeDatas.size() >= 30){
				ToasUtil.toast(mContext, "不能选择多于30个");
				return false;
			}
			knowledgeDatas.add(data);
			return true;
		} else {
			for (OrganizeInfoModel.KnowledgeBean bean : knowledgeDatas) {
				if (data.getCateId().equals(bean.getCateId())) {
					knowledgeDatas.remove(bean);
					break;
				}
			}
			return true;
		}
	}

	@Override
	protected void saveTabDatas() {

	}
}
